package com.feinno.urcs.group.siptask;

import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import com.feinno.urcs.offline.MessageService;
import com.feinno.urcs.offline.RegEvent;
import com.feinno.urcs.offline.SendMessageHandler;
import com.feinno.urcs.offline.servlet.OfflineMessageArgs;
import com.feinno.urcs.storage.MessageStorageService;
import com.feinno.urcs.storage.entity.MessageType;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.task.DedicatedTask;
import org.helium.framework.task.DedicatedTaskContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 这个地方其实不需要DedicatedTask 了. 因为离线的逻辑是依靠了原来T端SessionMode 的消息dialog 的逻辑.Invite 也是走原来T端逻辑了.
 *
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@TaskImplementation(event = GroupTaskEvents.OFFLINE_DISPATCH_TASK)
public class GroupOfflineMessageDispatchTask implements DedicatedTask<OfflineMessageArgs> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroupOfflineMessageDispatchTask.class);

    @ServiceSetter
    private MessageStorageService storageService;
    @ServiceSetter(id = "group:GroupSendTextMessageHandler")
    private SendMessageHandler sendTextMessageHandler;

    private MessageService messageService;

    @Override
    public void processTask(DedicatedTaskContext ctx, OfflineMessageArgs args) {
        if (messageService == null) {
            synchronized (this) {
                if (messageService == null) {
                    messageService = new MessageService(storageService, 100);
                    messageService.register(MessageType.BASE_MESSAGE, sendTextMessageHandler);
                    messageService.start();
                }
            }
        }

        try {
            RegEvent event = new RegEvent(args.getUser(), args.getUserImpi(), args.getRegType());
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(String.format("processTask: %s", event));
            }

            messageService.handle(event);

        } catch (Exception ex) {
            LOGGER.error("OfflineMessageTask processTask error.", ex);
        }

        ctx.setTaskRunnable();
    }

    @Override
    public void processTaskRemoved(DedicatedTaskContext ctx) {

    }
}
